package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"gitee.com/shipnet/serialer"

	"github.com/tarm/serial"
)

func main() {
	options := serial.Config{
		Name:     "/dev/ttyS1",
		Baud:     9600,
		Size:     8,
		StopBits: 1,
		// MinimumReadSize: 1,
	}

	port, err := serial.OpenPort(&options)
	if err != nil {
		log.Fatal(err)
	}
	defer port.Close()

	r := bufio.NewReader(port)
	go func() {
		for {
			bs, err := r.ReadBytes('\n')
			if err != nil {
				log.Printf("read error = %v\n", err)
			}
			fmt.Printf("read = %s\n", string(bs))
		}
	}()

	input := bufio.NewReader(os.Stdin)
	for {
		bs, err := input.ReadBytes('\n')
		if err != nil {
			log.Printf("read error = %v\n", err)
		}
		s := strings.TrimSpace(string(bs))
		ch := serialer.XorChecksumString([]byte(s))
		output := fmt.Sprintf("$%s*%s\r\n", s, ch)
		// fmt.Printf("output: %s\n", output)
		n, err := port.Write([]byte(output))
		if err != nil {
			fmt.Printf("output: %s, num = %d, err = %v\n", output, n, err)
		} else {
			fmt.Printf("output: %s, num = %d, err = nil", output, n)
		}
	}
}
